package com.msh.frame.client.util;

import com.msh.frame.client.define.StringDef;
import com.msh.frame.client.interfaces.IClassLoadLog;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * 启动时使用，后期没有作用
 */
@Slf4j
public class StartupUtil {

  public static void printLoadClass(Map<String, IClassLoadLog> classLoadLogMap){
    if(CollectionUtils.isEmpty(classLoadLogMap)){
      return;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(StringDef.NEWLINE);
    classLoadLogMap.entrySet().stream().forEach(e->{
      String info = e.getValue().logInfo();
      if(null != info){
        sb.append(info);
      }
    });
    if (sb.length() >= 2) {
      sb.delete(sb.length()-2, sb.length());
    }
    log.info(sb.toString());
  }

  public static void logApplicationStartup(Environment env) {
    String serverPort = env.getProperty("server.port");
    String contextPath = env.getProperty("server.servlet.context-path");
    if (StringUtils.isEmpty(contextPath)) {
      contextPath = "/";
    }
    String hostAddress = "localhost";
    try {
      hostAddress = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      log.warn("无法确定主机地址，使用默认值'localhost'.");
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\thttp://localhost:{}{}\n\t" +
            "External: \thttp://{}:{}{}\n\t" +
            "Profile(s): \t{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        serverPort,
        contextPath,
        hostAddress,
        serverPort,
        contextPath,
        env.getActiveProfiles());
  }
}
